import React, { useEffect } from 'react';
import { Space, Button, DatePicker } from 'antd';
import moment from 'moment';

import { useTRState, TjStation, TjSelect } from '@/pages/ETrade/components';
import { getContractList } from './services';
import { points } from './helper';

const defaultForm = (power) => {
  // 默认表单
  const dates =
    new Date().getDate() === 1
      ? [moment().add(-1, 'months').startOf('month'), moment().add(-1, 'months').endOf('month')]
      : [moment().startOf('month'), moment()];
  const provinceId = power?.[0]?.provinceId; // 省份id
  const marketId = power?.[0]?.marketId;
  const stationTree = power?.[0]?.children || []; // 交易单元
  const stationIdList = _.flattenDeep(stationTree.map((x) => x?.children?.map((y) => y.value)));
  return {
    provinceId, // 省份
    stationIdList, // 交易单元id（多选）
    stationTree,
    marketId,
    startDate: dates[0].format('YYYY-MM-DD'),
    endDate: dates[1].format('YYYY-MM-DD'),
    pointList: points.map(({ value }) => value),
  };
};

export default ({ power = [], onChange = () => {} }) => {
  const [state, setState] = useTRState({
    // 表单
    ...defaultForm(power),
    contractIdList: [], // 合约id（多选）
    searched: false, // 异步标识
    // 合约
    contracts: [],
    loading: false,
  });

  useEffect(() => {
    fetchContracts();
  }, [state.startDate, state.endDate, state.provinceId, JSON.stringify(state.stationIdList)]);

  const fetchContracts = async () => {
    // 获取合约
    setState({ loading: true });
    const { provinceId, startDate, endDate, stationIdList } = state;
    if (!provinceId) return;
    const res = await getContractList({ provinceId, startDate, endDate, stationIdList });
    const contracts = res?.contractList || [];
    const contractIdList = contracts.map(({ value }) => value);
    state.contractIdList = contractIdList;
    setState({
      contracts,
      contractIdList,
      loading: false,
    });
    !state.searched && _onFinish();
  };

  const onChangeRegion = (region) => {
    // 切换省份
    const provinceId = region?.provinceId; // 省份id
    const marketId = region?.marketId; // 交易中心id
    const stationTree = region?.children || []; // 交易单元
    const stationIdList = _.flattenDeep(
      stationTree.map((x) => x?.children?.map((y) => y.stationId)),
    );
    setState({
      marketId,
      provinceId,
      stationIdList,
      stationTree,
    });
  };

  const _onFinish = () => {
    // 查询
    setState({
      searched: true,
    });
    onChange?.({
      startDate: state.startDate,
      endDate: state.endDate,
      pointList: state.pointList,
      provinceId: state.provinceId,
      stationIdList: state.stationIdList,
      contractIdList: state.contractIdList,
    }); // 通知父级
  };

  const _onReset = () => {
    // 重置
    setState({
      ...defaultForm(power),
      searched: false,
    });
  };

  return (
    <Space size={16} wrap>
      <TjSelect
        style={{ width: 200 }}
        value={state.marketId}
        options={power}
        onChange={(v, temp) => onChangeRegion(temp)}
        showSearch
        filterOption={(input, option) => {
          return (option?.label).toLowerCase().includes(input.toLowerCase());
        }}
      />
      <TjStation
        style={{ width: 200 }}
        value={state.stationIdList}
        options={state.stationTree}
        onChange={(stationIdList) => setState({ stationIdList })}
      />
      <DatePicker.RangePicker
        style={{ width: 256 }}
        value={[moment(state.startDate), moment(state.endDate)]}
        separator="-"
        format={'YYYYMMDD'}
        allowClear={false}
        onChange={(dates) =>
          setState({
            startDate: dates[0].format('YYYY-MM-DD'),
            endDate: dates[1].format('YYYY-MM-DD'),
          })
        }
      />
      <TjSelect
        value={state.contractIdList}
        options={state.contracts}
        onChange={(contractIdList) => setState({ contractIdList })}
        mode="multiple"
        label="合约"
        style={{ width: 400 }}
        loading={state.loading}
      />
      <TjSelect
        value={state.pointList}
        options={points}
        onChange={(pointList) => setState({ pointList })}
        mode="multiple"
        label="时点"
        style={{ width: 200 }}
      />
      <Space size={16}>
        <Button
          disabled={state.loading || !state.contracts.length}
          style={{ width: 98, height: 32 }}
          type="primary"
          onClick={_onFinish}
        >
          查询
        </Button>
        <Button
          disabled={state.loading || !state.contracts.length}
          style={{ width: 98, height: 32 }}
          ghost
          onClick={_onReset}
        >
          重置
        </Button>
      </Space>
    </Space>
  );
};
